package top.abrsm.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * 阿里云短信发送工具类
 */
@Slf4j
public class AliSMS {


    /**
     * 生成随机的6位数，短信验证码
     * @return
     */
    public static String getMsgCode () {
        int n = 6;
        StringBuilder code = new StringBuilder ();
        Random ran = new Random ();
        for ( int i = 0; i < n; i++ ) {
            code.append ( Integer.valueOf ( ran.nextInt ( 10 ) ).toString () );
        }
        return code.toString ();
    }


    /**
     * 发送登录验证码
     * @param phoneNumber：手机
     * @param code：验证码
     * @return
     */
    public static String sendMSM (String phoneNumber, String code) {
        DefaultProfile profile = DefaultProfile.getProfile ( "cn-shanghai", ConstUtil.accessKeyId, ConstUtil.accessKeySecret );
        IAcsClient client = new DefaultAcsClient ( profile );

        CommonRequest request = new CommonRequest ();
        request.setSysMethod ( MethodType.POST );
        request.setSysDomain ( "dysmsapi.aliyuncs.com" );
        request.setSysVersion ( "2017-05-25" );
        request.setSysAction ( "SendSms" );
        request.putQueryParameter ( "PhoneNumbers", phoneNumber );
        request.putQueryParameter ( "SignName", "TOP英皇乐理" );
        request.putQueryParameter ( "TemplateCode", "SMS_235812023" );
        request.putQueryParameter ( "TemplateParam", "{\"code\":\"" + code + "\"}" );
        try {
            CommonResponse response = client.getCommonResponse ( request );
            log.info ( "发送验证码成功 -> [{}]", response.getData () );
            return response.getData ();
        } catch ( ServerException e ) {
            log.error ( "发送验证码异常 -> [{}]", e );
        } catch ( ClientException e ) {
            log.error ( "发送验证码异常 -> [{}]", e );
        }
        return null;
    }


}